package com.atguigu.gmall.payment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.Date;

/**
 * @Author atguigu-mqx
 * @Description TODO
 * @Date 2023/5/27 15:33
 * @Version 1.0
 */
@Service
public class AlipayServiceImpl implements AlipayService {

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private RabbitService rabbitService;
//      还需要保存支付交易记录。主要功能生成二维码！
    @Override
    public String createPay(Long orderId) throws AlipayApiException {
        // 根据订单Id获取订单对象
        OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId);
        //  判断订单状态.
        if ("CLOSED".equals(orderInfo.getOrderStatus()) || "PAID".equals(orderInfo.getOrderStatus())){
            return "当前订单已关闭或已支付";
        }
        //  保存交易记录.
        paymentService.savePaymentInfo(orderInfo, PaymentType.ALIPAY.name());

        //  生成二维码.
        //  AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","app_id","your private_key","json","GBK","alipay_public_key","RSA2");
        //  获取到支付请求对象
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //异步接收地址，仅支持http/https，公网可访问
        request.setNotifyUrl(AlipayConfig.notify_payment_url);
        //同步跳转地址，仅支持http/https
        request.setReturnUrl(AlipayConfig.return_payment_url);
        /******必传参数******/
        JSONObject bizContent = new JSONObject();
        //商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        //支付金额，最小值0.01元
        bizContent.put("total_amount", 0.01);
        //订单标题，不可使用特殊符号
        bizContent.put("subject", orderInfo.getTradeBody());
        //电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        //  日期时间对象
        ZonedDateTime zonedDateTime = LocalDateTime.now().plusMinutes(10).atZone(ZoneId.systemDefault());
        Date date = Date.from(zonedDateTime.toInstant());
        System.out.println(date);

        //  订单的过期时间： orderInfo.getExpireTime();  date 二维码过期时间.  orderInfo.getExpireTime() +1天;
        //        ZonedDateTime zonedDateTime1 = LocalDateTime.now().plusSeconds(5).atZone(ZoneId.systemDefault());
        //        orderInfo.setExpireTime(Date.from(zonedDateTime1.toInstant()));
        //        int result = DateUtil.truncatedCompareTo(date, orderInfo.getExpireTime(), Calendar.SECOND);
        //        if (result==1){
        //            bizContent.put("time_expire", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(orderInfo.getExpireTime()));
        //        }else {
        //            bizContent.put("time_expire", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
        //        }
//        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date)); 可选：
        bizContent.put("time_expire", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));


        //  将参数变为json 字符串存储.
        request.setBizContent(bizContent.toString());
        //  要使用form 生成二维码！直接渲染到页面. form 就是一个表单.
        String form = alipayClient.pageExecute(request).getBody();
        //  返回数据
        return form;
    }

    @Override
    public Boolean refund(Long orderId) {
        //  根据订单Id 获取
        OrderInfo orderInfo = this.orderFeignClient.getOrderInfo(orderId);
        if (null == orderInfo){
            return false;
        }
        //  AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","app_id","your private_key","json","GBK","alipay_public_key","RSA2");
        //  获取退款情况
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        bizContent.put("refund_amount", 0.01);
//        bizContent.put("out_request_no", "HZ01RF001");
        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if(response.isSuccess()){
            //  精准判断
            if ("Y".equals(response.getFundChange())){
                //  需要修改交易记录状态 -- 订单状态;
                //  调用修改交易状态方法.
                PaymentInfo paymentInfo = new PaymentInfo();
                paymentInfo.setPaymentStatus(PaymentStatus.CLOSED.name());
                this.paymentService.updatePaymentStatus(paymentInfo,orderInfo.getOutTradeNo(),PaymentType.ALIPAY.name());
                //  发送消息修改订单状态.
                this.rabbitService.sendMsg(MqConst.EXCHANGE_DIRECT_ORDER_CLOSED,MqConst.ROUTING_ORDER_CLOSED,orderInfo.getId());

                return true;
            }else {
                return false;
            }
        } else {
            return false;
        }
    }

    @Override
    public Boolean closePay(Long orderId) {
        //  获取orderInfo 对象
        OrderInfo orderInfo = this.orderFeignClient.getOrderInfo(orderId);
        if (null == orderInfo) return false;
        //  创建关闭支付宝交易的对象
        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        request.setBizContent(bizContent.toString());
        AlipayTradeCloseResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if(response.isSuccess()){
            return true;
        } else {
            return false;
        }

    }

    @Override
    public Boolean checkPayment(Long orderId) {
        //  获取orderInfo 对象
        OrderInfo orderInfo = this.orderFeignClient.getOrderInfo(orderId);
        if (null == orderInfo) return false;
        //  创建查询请求对象
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        request.setBizContent(bizContent.toString());
        AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if(response.isSuccess()){
            //  当前订单的状态.
            System.out.println("交易状态:"+response.getTradeStatus());
            return true;
        } else {
            return false;
        }
    }
}
